//
//  Paginatable+Additions.swift
//  App
//
//  Created by melvyn on 2018/8/22.
//

import Foundation
import Fluent
import Vapor
import Pagination

extension QueryBuilder where Result: Paginatable, Result.Database == Database {
    func paginate(page: Int, per: Int = Result.defaultPageSize, _ sorts: [Result.Database.QuerySort] = Result.defaultPageSorts) throws -> Self {
        
        guard page > 0 else {
            throw PaginationError.invalidPageNumber(page)
        }
        
        // Require page 1 or greater
        let page = page > 0 ? page : 1
        
        // For now until https://github.com/vapor/fluent/issues/518 is fixed, this is the work around.

        let lowerBound = (page - 1) * per
        Database.queryRangeApply(lower: lowerBound, upper: lowerBound + per, to: &self.query)
        for sort in sorts {
            Database.querySortApply(sort, to: &self.query)
        }
        
        return self
    }
    
    func paginate(for req: Request, pageKey: String = Pagination.defaultPageKey, perPageKey: String = Pagination.defaultPerPageKey, _ sorts: [Result.Database.QuerySort] = Result.defaultPageSorts) throws -> Self {
        
        let page = try req.query.get(Int?.self, at: pageKey) ?? 1
        var per = try req.query.get(Int?.self, at: perPageKey) ?? Result.defaultPageSize
        if let maxPer = Result.maxPageSize, per > maxPer {
            per = maxPer
        }
        
        return try self.paginate(page: page, per: per, sorts)
    }
}

extension QueryContainer {
    
}
